package com.gdou.crrp.controller;

import com.gdou.crrp.entity.*;
import com.gdou.crrp.service.CommunityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/community")
public class CommunityController {

    static Logger logger = LoggerFactory.getLogger(CommunityController.class);

    @Autowired
    private CommunityService communityService;

    //显示所有帖子，并进行分页
    @RequestMapping("/toCommunity")
    public String toCommunity(Map<String,Object> map, Integer pn,HttpSession session){
        if (pn == null){
            pn = 0;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");//排序
        Pageable pageable = PageRequest.of(pn,5,sort);
        Page<Topic> topicList = communityService.showTopic(pageable);
        logger.info("pageNum==" + pn);
        int uid = getUid(session);
        map.put("uid",uid);
        map.put("pageInfo", topicList);
        return "community";
    }

    //点击任一帖子，跳转帖子页面
    @RequestMapping("/toTopic/{id}")
    public String toTopic(@PathVariable("id") Integer id,Map<String,Object> map,HttpSession session){
        Topic topic = communityService.toTopic(id);
        User user = communityService.findUser(topic.getUid());
        List<Comment> comments = communityService.showComment(id);
        int uid = getUid(session);
        TopicCollect topicCollect = communityService.findByTidAndUid(id,uid);
        List<CommentReply> commentReplies = communityService.showCommentReply(id);
        map.put("commentReplies",commentReplies);
        map.put("topicCollect",topicCollect);
        map.put("uid",uid);
        map.put("name",user.getName());
        map.put("topic",topic);
        map.put("commentlist",comments);
        return "topic";
    }

    //在帖子列表页面输入帖子内容，发表帖子
    @RequestMapping("/sendTopic")
    public String sendTopic(@RequestParam("title") String title,@RequestParam("content") String content,HttpSession session){
        int uid = getUid(session);
        communityService.saveTopic(title,content,uid);
        return "redirect:/community/toCommunity";
    }

    //删除帖子
    @RequestMapping("/deleteTopic/{id}")
    public String deleteTopic(@PathVariable("id")Integer id,HttpSession session,Map<String,Object> map){
        int uid = getUid(session);
        communityService.deleteTopic(id);
        communityService.deleteCollect(id,uid);
        map.put("uid",uid);
        return "redirect:/community/toCommunity";
    }

    //评论
    @RequestMapping("/sendComment/{tid}")
    public String sendComment(Comment comment,@PathVariable("tid")Integer tid,HttpSession session){
        int uid = getUid(session);
        User user = communityService.findUser(uid);
        comment.setName(user.getName());
        communityService.sendComment(comment,tid);
        String url = "redirect:/community/toTopic/"+comment.getTid();
        return url;
    }

    //评论回复
    @RequestMapping("/sendCommentReply")
    public String sendCommentReply(@RequestParam("comments")String comments,@RequestParam("cid") Integer cid, HttpSession session){
        int uid = getUid(session);
        User user = communityService.findUser(uid);
        String name = user.getName();
        Comment comment = communityService.findComment(cid);
        communityService.sendCommentReply(comments,cid,name,comment.getTid());
        String url = "redirect:/community/toTopic/"+comment.getTid();
        return url;
    }

    //评论回复的回复
    @RequestMapping("/replyCommentReply")
    public String replyCommentReply(@RequestParam("comments")String comments,@RequestParam("cid") Integer cid,@RequestParam("parentId")Integer parentId,@RequestParam("replyName")String replyName, HttpSession session){
        int uid = getUid(session);
        User user = communityService.findUser(uid);
        String name = user.getName();
        CommentReply commentReply = communityService.findCommentReply(parentId);
        communityService.replyCommentReply(comments,cid,name,commentReply.getTid(),parentId,replyName);
        String url = "redirect:/community/toTopic/"+commentReply.getTid();
        return url;
    }

    //通过标题查询帖子，并进行分页
    @RequestMapping("/findTopicByTitle")
    public String findTopicByTitle(@RequestParam("title") String title,
                                   Integer pn,
                                   Map<String,Object> map){
        if (pn == null){
            pn = 0;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");//排序
        Pageable pageable = PageRequest.of(pn,5,sort);
        Page<Topic> topics = communityService.findTopicByTitle(title,pageable);
        map.put("title",title);
        map.put("topiclist",topics);
        return "findTopic";
    }

    //收藏帖子，保存到个人中心
    @ResponseBody
    @PostMapping("/collectTopic")
    public Map<String,Object> collectTopic(@RequestParam Integer tid,HttpSession session){
        Topic topic = communityService.toTopic(tid);
        List<Comment> comments = communityService.showComment(tid);
        int uid = getUid(session);
        List<TopicCollect> topicCollectList = communityService.findCollectTopic(uid);
        User user = communityService.findUser(uid);
        int count = 0;
        for (TopicCollect topicCollectList1 : topicCollectList){
            if (topicCollectList1.getTid() == topic.getId() && topicCollectList1.getUid() == uid ){
                count++;
            }
        }
        if (count == 0){
            communityService.collectTopic(tid,uid);
        }
        if (count == 1){
            communityService.deleteCollect(tid,uid);
        }
        TopicCollect topicCollect = communityService.findByTidAndUid(tid,uid);
        Integer ctid;
        Integer cuid;
        if (topicCollect == null){
            ctid = 0;
            cuid = 0;
        }else {
            ctid = topicCollect.getTid();
            cuid = topicCollect.getUid();
        }
        List<CommentReply> commentReplies = communityService.showCommentReply(tid);
        Map<String, Object> map = new HashMap<>();
        map.put("commentReplies",commentReplies);
        map.put("cuid",cuid);
        map.put("ctid",ctid);
        map.put("commentlist",comments);
        map.put("topic",topic);
        map.put("name",user.getName());
        map.put("suid",uid);
        return map;
    }

    //跳转去个人中心查看收藏的帖子
    @RequestMapping("/toCollection")
    public String showCollectTopic(Map<String,Object> map,HttpSession session){
        List<Topic> topicCollectList = communityService.showCollectTopic();
        int uid =getUid(session);
        map.put("uid",uid);
        map.put("topicCollectList",topicCollectList);
        return "collection";
    }

    /*
    ================================================================================================
    ================================================================================================
    -----------------------------          文章             ----------------------------------------
    ================================================================================================
    ================================================================================================
     */

    //发表文章
    @RequestMapping("/sendArticle")
    public String sendArticle(Article article,HttpSession session){
        int uid = getUid(session);
        article.setUid(uid);
        communityService.saveArticle(article);
        return "redirect:/community/showArticle";
    }

    //跳转填写文章信息页面
    @RequestMapping("/toSendArticle")
    public String toSendArticle(){
        return "writeArticle";
    }

    //显示所有文章，并进行分页
    @RequestMapping("/showArticle")
    public String showArticle(Map<String,Object> map, Integer pn,HttpSession session){
        if (pn == null){
            pn = 0;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");//排序
        Pageable pageable = PageRequest.of(pn,5,sort);
        Page<Article> list = communityService.showArticle(pageable);
        logger.info("pageNum==" + pn);
        int uid = getUid(session);
        map.put("uid",uid);
        map.put("pageInfo", list);
        return "allArticle";
    }

    //根据id跳转文章内容页面
    @RequestMapping("/toArticle/{id}")
    public String toArticle(Map<String,Object> map,@PathVariable("id")Integer id,HttpSession session){
        Article article = communityService.toArticle(id);
        User user = communityService.findUser(article.getUid());
        List<ArticleComment> articleComments = communityService.showArticleComment(id);
        int uid = getUid(session);
//        ArticleCollect articleCollect = communityService.findByAidAndUid(id,uid);
////        map.put("articleCollect",articleCollect);
        map.put("uid",uid);
        map.put("articleComments",articleComments);
        map.put("name",user.getName());
        map.put("article",article);
        return "article";
    }

    //评论
    @RequestMapping("/sendArticleComment/{aid}")
    public String sendArticleComment(ArticleComment articleComment,@PathVariable("aid")Integer aid,HttpSession session){
        int uid = getUid(session);
        User user = communityService.findUser(uid);
        articleComment.setName(user.getName());
        communityService.sendArticleComment(articleComment,aid);
        String url = "redirect:/community/toArticle/"+articleComment.getAid();
        return url;
    }

    //通过标题查询文章，并进行分页
    @RequestMapping("/findArticleByTitle")
    public String findArticleByTitle(@RequestParam("title") String title,
                                     Integer pn,
                                     Map<String,Object> map){
        if (pn == null){
            pn = 0;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");//排序
        Pageable pageable = PageRequest.of(pn,5,sort);
        Page<Article> articles = communityService.findArticleByTitle(title,pageable);
        map.put("title",title);
        map.put("articleList",articles);
        return "findArticle";
    }

    //收藏文章，保存到个人中心
    @ResponseBody
    @RequestMapping("/collectArticle")
    public Map<String, Object> collectArticle(@RequestParam Integer aid,HttpSession session){
        int uid = getUid(session);
        Article article = communityService.toArticle(aid);
        List<ArticleComment> articleComments = communityService.showArticleComment(aid);
        User user = communityService.findUser(uid);
        List<ArticleCollect> articleCollectList = communityService.findCollectArticle(uid);
        int i = 0;
        for (ArticleCollect articleCollects : articleCollectList){
            if (articleCollects.getAid() == article.getId() && articleCollects.getUid() == uid) {
                i++;
            }
        }
        if (i == 0) {
            communityService.collectArticle(aid,uid);
        }
        if (i == 1) {
            communityService.deleteArticleCollect(aid, uid);
        }
        ArticleCollect articleCollect = communityService.findByAidAndUid(aid,uid);
        Integer caid;Integer auid;
        if (articleCollect == null) {
            caid = 0;
            auid = 0;
        }else{
            caid = articleCollect.getAid();
            auid = articleCollect.getUid();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("caid",caid);
        map.put("auid",auid);
        map.put("suid",uid);
        map.put("articleComments",articleComments);
        map.put("article",article);
        map.put("name",user.getName());
        return map;
    }

    /*
    ==========================================================================================================
    =====================================       通用方法          ============================================
    ==========================================================================================================
    */
    public Integer getUid(HttpSession session){
//        session.setAttribute("uid",1);
        String id = session.getAttribute("id").toString();
        int uid = Integer.parseInt(id);
        return uid;
    }
}
